<?php

namespace app\admin\controller\shops;

use app\common\controller\Backend;
use think\Db;
use app\common\model\Config;
use app\admin\model\Admin;

/**
 * 重复订单
 *
 * @icon fa fa-circle-o
 */
class Repetitive extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->alias('order')
                    ->where($where)
                    ->field('*,count(wm_order_sn) as num,group_concat(is_yunzhan) as platform,group_concat(play_order_no) as play_order_nos,shop.id as shop_id,order.id as order_id')
                    ->join('chbc_shop shop','shop.shop_no=order.shop_no')
                    ->where('order.order_status in (-9,-8,-7,-4,-3,-1,3,6)')
                    ->group('order.wm_order_sn')
                    ->having('count(order.wm_order_sn)>1')
                    ->order('place_time DESC')
                    ->paginate($limit);
            foreach ($list as &$row) {
                $row['id'] = $row['order_id'];
                $platform = explode(',', $row['platform']);
                $play_order_nos = explode(',', $row['play_order_nos']);
                $row['platform']='';
                foreach ($platform as $key => $value) {
                    if ($key>0) $row['platform'] .= '</br>';
                    if ($value==0) {
                        $row['platform'] .= '渠道：吃喝不愁，订单号：'.$play_order_nos[$key];
                    } else {
                        $row['platform'] .= '渠道：'.Db::name('channel')->where('id',$value)->value('name').'，订单号：'.$play_order_nos[$key];
                    }
                }
                // 处理状态
                $repetitive=Db::name('repetitive')->where(['wm_order_sn'=>$row['wm_order_sn']])->find();
                if ($repetitive) {
                    $row['order_status']=1;
                    $row['create_by'] = $repetitive['create_by'];
                } else {
                    $row['order_status']=0;
                    $row['create_by'] = '';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $salesmanList = [];
        $salesman = $this->salesmanList();
        foreach ($salesman as $key => $value) {
            $salesmanList[$value['nickname']] = $value['nickname'];
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $play_order = Db::name('play_order')->where('id',$ids)->find();
        $play_orders = Db::name('play_order')->where(['wm_order_sn'=>$play_order['wm_order_sn']])->select();
        $row = ['shop_name'=>$play_order['shop_name'],'wm_order_sn'=>$play_order['wm_order_sn']];
        $row['platform'] = '';
        foreach ($play_orders as $key => $value) {
            if ($key>0) $row['platform'] .= '</br>';
            $row['platform'] .= '渠道：'.Db::name('channel')->where('id',$value['is_yunzhan'])->value('name').'，订单号：'.$value['play_order_no'];
        }
        // 处理状态
        $repetitive=Db::name('repetitive')->where(['wm_order_sn'=>$play_order['wm_order_sn']])->find();
        if ($repetitive) {
            $row['order_status']='已处理';
            $row['create_by'] = $repetitive['create_by'];
        } else {
            $row['order_status']='未处理';
            $row['create_by'] = '';
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function agree($ids = null)
    {
        $play_order = Db::name('play_order')->where('id',$ids)->find();
        $play_orders = Db::name('play_order')->where(['wm_order_sn'=>$play_order['wm_order_sn']])->select();
        $data = [
            'wm_order_sn' => $play_order['wm_order_sn'],
            'status' => 1,
            'create_dt' => date('Y-m-d H:i:s'),
            'create_by' => $this->auth->nickname,
            'update_dt' => date('Y-m-d H:i:s'),
        ];
        Db::startTrans();
        try {
            Db::name('repetitive')->insert($data);
            $orderid=0;// 生效订单id，如果有吃喝不愁渠道使吃喝不愁生效其他失效，如果没有吃喝不愁渠道随机生效一个
            foreach ($play_orders as $key => $value) {
                if ($value['is_yunzhan']==0) {
                    $orderid=$value['id'];break;
                }
            }
            if (!$orderid) $orderid=$value['id'];
            Db::name('play_order')->where(['wm_order_sn'=>$play_order['wm_order_sn'],'id'=>['<>',$orderid]])->update(['is_effect'=>0]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('处理失败');
        }
        $this->success();
    }

}
